<template>
  <basic-container>
    <div class="header">
      <TitleComponent mainTitle="刷单商品" subTitle="列表" />
      <el-button text type="primary" @click="router.push('/index')">主页</el-button>
    </div>
    <div class="tab_box">
      <span class="head">专区</span>
      <span class="tab_item" @click="changeTab(item, index)" v-for="(item, index) in tabs" :key="index"
        :class="{ active: currentIndex === index }">{{ item.name }} </span>
    </div>
    <div class="crud_content">
      <avue-crud :option="option" :table-loading="crudData.loading" :data="crudData.data" :page.sync="crudData.page"
        v-model="crudData.form" ref="crud" :before-open="beforeOpen" @search-change="searchChange"
        @search-reset="searchReset" @selection-change="selectionChange" @refresh-change="refreshChange" @row-del="rowDel"
        @on-load="onLoad">
        <template #zq-header="{ }">
          <span>专区 </span>
        </template>
        <template #link="{ row }">
          <a style="color: #4e9876;" href="javascript:void(0);"> <span @click="openLink(row)">点击</span></a>
        </template>
        <template #link-form="">
          <el-input v-model="crudData.form.link" style="max-width: 600px" placeholder="Please input"
            class="input-with-select">
            <template #prepend>
              <img src="@/assets/ie.png" alt="">
            </template>
          </el-input>
        </template>
        <template #menu-form="{ size }">
          <div class="btns_box">
            <el-button icon="el-icon-delete" @click="handleEmpty">取消</el-button>
            <div class="right_box">
              <!-- <el-checkbox v-model="crudData.form.edit" label="继续编辑" size="large"/>
              <el-checkbox v-model="crudData.form.creat" label="继续创建" size="large"/>
              <el-checkbox v-model="crudData.form.view" label="查看" size="large" class="view_btn"/> -->
              <el-button icon="el-icon-user" type="primary" @click="handleSubmit">提 交</el-button>
            </div>
          </div>
        </template>
        <template #menu="{ row }">
          <el-dropdown @command="(command) => handleCommand(command, row)">
            <el-icon style="rotate: 90deg;cursor: pointer" size="20">
              <More />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #menu-left="{ row }">
          <el-button class="btn" type="danger" @click="delsHandler" v-if="ids.length">
            批量删除
          </el-button>
          <el-button class="btn" type="success" @click="uploadHandler">
            上传EXCEL并导入数据
          </el-button>
        </template>
      </avue-crud>
    </div>
    <el-dialog v-model="crudData.confirmDeleteVisible" title="" width="440" destroy-on-close center class="custom-dialog">
      <div class="swal2-header">
        <div class="swal2-icon swal2-question swal2-animate-question-icon"></div>
        <div class="swal2_fs">确认删除？</div>
      </div>
      <div class="swal2_he">ID - {{ crudData.delIds }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#488C6D" class="btn btn-primary" @click="handleDeleteConfirm">
            确认
          </el-button>
          <el-button class="btn" type="" @click="handleDeleteCancel">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="crudData.excelBox" title="" width="440" destroy-on-close center class="custom-dialog">
      <div class="swal2-header">
        <avue-form v-model="crudData.uploadForm" :option="optionUpload" :upload-before="uploadBefore"
          :upload-after="uploadAfter" @submit="submitHandler">
          <template #download>
            <el-button type="primary" @click="downloadHandler">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
          <template #picture>
            <el-upload ref="upload" v-model:file-list="crudData.fileList" class="upload-demo" :data="crudData.picData"
              :action="crudData.action" :multiple="false" limit="1" :auto-upload="true" :on-change="onChange"
              :before-upload="beforeUpload">
              <el-button type="primary">上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500KB.
                </div>
              </template>
            </el-upload>
          </template>
        </avue-form>
      </div>
    </el-dialog>
  </basic-container>
</template>
<script setup lang="ts" name="taskDetail">
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, reactive, ref } from 'vue';
import { getList, remove, update, save, getListTab, importData } from "@/api/refersh/goodsList.js";

import TitleComponent from "@/components/title/index.vue";

const crud = ref('')
const upload = ref('')
const ids = computed(() => (crudData.selectionList.map(item => item.id)))
import Cookies from 'js-cookie'
import BasicContainer from "@/components/basic-container/main.vue";
import { useRouter } from "vue-router";
const router = useRouter();
const tabs = ref([])
const currentIndex = ref(-1)
let option: any = reactive({
  rowKey: 'id',
  height: 'auto',
  calcHeight: '8',
  searchShow: true,
  searchMenuSpan: 6,
  updateBtn: false,
  tip: false,
  border: true,
  excelBtn: true,
  index: false,
  viewBtn: false,
  editBtn: false,
  menuWidth: 100,
  delBtn: false,
  addBtn: true,
  dialogWidth: '40%',
  menuFixed: 'right',
  labelWidth: 130,
  menu: true,
  selection: true,
  searchLabelWidth: 110,
  indexLabel: '序号',
  saveBtnText: '确定',
  refreshBtn: true, // 刷新按钮
  columnBtn: false,
  searchShowBtn: false,
  indexWidth: 60,
  align: 'center',
  filterBtn: false,
  saveBtn: false,
  cancelBtn: false,
  column: [
    {
      label: "ID",
      prop: "id",
      sortable: true,
      disabled: true,

      search: true,
      addDisplay: false,
      span: 24,
    },
    {
      label: "标签",
      prop: "label",

      hide: true,
      type: 'checkbox',
      dicData: [{
        label: '喜欢',
        value: '1'
      }, {
        label: '订阅',
        value: '2'
      }, {
        label: '分享',
        value: '3'
      }],
      value: ['1', '2', '3'],
      span: 24,
      order: 1,
    },
    {
      label: "商品分类",
      prop: "zq",
      type: 'select',
      order: 2,
      search: false,

      dicData: tabs,
      props: {
        label: 'name',
        value: 'id'
      },
      span: 24,
      rules: [
        {
          required: true,
          message: '请输入专区',
          trigger: 'blur',
        },
      ],
    },
    {
      label: "总量",
      prop: "gross",
      type: 'number',
      value: 0,
      controlsPosition: 'top',
      span: 24,
    },
    {
      label: "剩余量",
      prop: "residueGross",
      value: 0,

      type: 'number',
      controlsPosition: 'top',
      span: 24,
    },
    {
      label: "审核时间（小时）",
      prop: "auditTime",
      type: 'number',
      value: 0,

      controlsPosition: 'top',
      span: 24,
    },
    {
      label: "链接",
      search: true,

      prop: "link",
      span: 24,
    },
    {
      label: "创建时间",
      prop: "createTime",
      type: 'datetime',
      hide: true,
      disabled: true,
      span: 24,
      addDisplay: false,

    },
    {
      label: "更新时间",
      prop: "updateTime",

      disabled: true,
      type: 'datetime',
      sortable: true,
      addDisplay: false,
      span: 24,
    }
  ]
})
let crudData: any = reactive({
  currentItem: {},
  action: '/prod-api/Commodity/importData',
  formData: new FormData(),
  fileList: [],
  picData: {},
  file: null,
  zoneName: '',
  zoneId: '',
  excelBox: false,
  loading: true,
  delIds: '',
  selectionList: [],
  confirmDeleteVisible: false,
  form: {
    edit: true,
    creat: "",
    view: "",
  },
  page: {
    pageSize: 10,
    currentPage: 1,
    total: 1,

  },
  openTyep: '',
  query: {},
  data: []
})
function downloadHandler() {
  window.open('/cdn/商品模板.xlsx')
}
const checkHandler = () => {
  if (!crudData.uploadForm.fenelei) {
    return ElMessage.warning('请先选择商品分类');
  } else {
    console.log('aaaa', upload.value);

    upload.value.$refs.input.click();
  }
}
const onChange = (res, fileList) => {

  console.log('ddddd', fileList);
  crudData.fileList = fileList
  crudData.uploadForm.picture = '1'
  crudData.excelBox = false
  onLoad(crudData.page)
  // crudData.formData.append('file',res.raw)
}
const optionUpload = reactive({
  // labelWidth: 130,
  submitBtn: false,
  emptyBtn: false,
  column: [
    {
      label: '商品分类',
      prop: 'fenelei',
      dicData: tabs,
      type: 'select',
      span: 24,
      props: {
        label: 'name',
        value: 'id'
      },
      rules: [
        {
          required: true,
          message: '请选择商品分类',
          trigger: 'blur',
        },
      ],
      change: ({ item, value }) => {
        if (value) {
          crudData.picData = {
            zoneId: value
          }
        }
      }
    },
    {
      label: '下载模板',
      prop: 'download'
    },
    {
      label: "数据文件",
      prop: "picture",
      slot: true,
      hide: true,
      type: 'upload',
      multiple: true,
      width: 210,
      listType: false,
      headers: {
        'Authorization': Cookies.get("Admin-Token")
      },
      limit: 1,
      propsHttp: {
        name: 'originalFilename',
        url: 'url',
      },
      autoUpload: true,
      data: {
        zoneId: 29
      },
      accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel',
      action: '',
      span: 24,
      rules: [
        {
          required: true,
          message: '请选择数据文件',
          trigger: 'blur',
        },
      ],
    },
  ]
})
const beforeUpload = (file, fileList) => {
  // console.log('file===11111111', fileList);
  // if (!crudData.uploadForm.fenelei) {
  //   ElMessage.warning('请先选择商品分类');
  //   return false
  // } else {
  //   return true
  // }

}
const uploadBefore = (file, done, loading, column) => {
  crudData.file = file
  done()
}
const handleFileChange = (file) => {

}
const uploadAfter = (res, done, loading, column) => {
  done()
}
const submitHandler = async () => {
  // let formData = new FormData()
  // formData.append('file', crudData.fileList[0].raw);
  // formData.append('zoneId', crudData.zoneId);
  // console.log('formData====', formData);

  // await importData(formData)
}
const uploadHandler = () => {
  crudData.excelBox = true
}
const openLink = (row) => {
  window.open(row.link)
}
const handleDeleteConfirm = async () => {
  await remove(crudData.delIds)
  crudData.confirmDeleteVisible = false;
  onLoad(crudData.page)
}
const handleCommand = (command, row) => {
  crudData.rowData = row
  if (command === 'edit') {
    crud.value.rowEdit(row)
  } else if (command === 'delete') {
    crudData.confirmDeleteVisible = true;
    crudData.delIds = row.id
  }
}

const searchChange = (params, done) => {
  crudData.query = params;
  crudData.page.currentPage = 1;
  onLoad(crudData.page)
  done();
}
const searchReset = () => {
  crudData.query = {};
  onLoad(crudData.page)
}
const selectionChange = (list) => {
  crudData.selectionList = list
}
const refreshChange = () => {
  onLoad(crudData.page);
}
const delsHandler = async () => {

  crudData.confirmDeleteVisible = true
  let id = ids.value
  console.log('ids', ids);
  crudData.delIds = id.join(',')
}
const handleDeleteCancel = () => {
  crudData.confirmDeleteVisible = false;
}
const handleEmpty = () => {
  crud.value.resetForm()
}
const beforeOpen = (done, type) => {
  crudData.openTyep = type
  done()
}
const handleSubmit = () => {
  crud.value.validate(async (valid: any, done: () => void, msg: any) => {
    if (valid) {
      if (crudData.openTyep === 'add') {
        crudData.form = Object.assign(crudData.form, { label: crudData.form.label.join(',') })
      }
      let submit = save
      if (crudData.form.id) {
        submit = update
      }
      await submit(crudData.form)
      ElMessage.success('操作成功');
      crud.value.closeDialog()
      onLoad(crudData.page);
    }
  })
}
const changeTab = (item, index) => {
  currentIndex.value = index
  crudData.query.zq = item.id
  onLoad(crudData.page, { zq: item.id })

}
// 序号按钮提交
const orderSubmit = (row: { visible: boolean; }) => {
  row.visible = false
  console.log('row====', row);
}
// 删除
const rowDel = (form, index, done) => {
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage.success("删除成功");
      done(form); // 删除逻辑，此处暂未实现删除功能
    })
    .catch(() => {
    });
};

const onLoad = (page, params = {}) => {
  crudData.loading = true;
  getList(page.currentPage, page.pageSize, Object.assign(params, crudData.query)).then(res => {
    console.log('getReviewLog--', res);
    const Data = res.data;
    crudData.page.total = Data.total;
    crudData.data = Data.records;
    crudData.loading = false;
  });
}
const onLoadTab = (page, params = {}) => {
  getListTab(page.currentPage, 999).then(res => {
    console.log('getReviewLog--', res);
    const Data = res.data;
    tabs.value = Data.records
    let zq = option.column.find(item => item.prop === 'zq')
    zq.dicData = tabs.value
    // changeTab(tabs.value[0], 0)
  });
}
onLoadTab(crudData.page)
</script>
<style scoped lang="scss">
.tab_box {
  width: 100%;
  padding: 15px 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  background-color: #fff;
  border: 1px solid #ccc;

  .head {
    margin-left: 30px;
  }

  .tab_item {
    cursor: pointer;
    margin-left: 30px;

    &.active {
      color: #458769;
    }
  }
}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 2%;
}

.crud_content {
  width: 100%;
}

.btns_box {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .view_btn {
    margin-right: 20px;
  }
}

.custom-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.swal2-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.swal2-icon {
  position: relative;
  box-sizing: content-box;
  justify-content: center;
  width: 5em;
  height: 5em;
  margin: 1.25em auto 1.875em;
  zoom: normal;
  border: 0.25em solid transparent;
  border-radius: 50%;
  line-height: 5em;
  cursor: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.swal2-icon.swal2-question::before {
  content: "?";
}

.swal2-icon::before {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 92%;
  font-size: 3.75em;
}

.swal2-icon.swal2-question {
  border-color: #c9dae1;
  color: #87adbd;
}

.swal2_fs {
  margin: 0 0 0.4em;
  padding: 0;
  font-size: 25px;
  color: #595959;
  text-align: center;
  font-weight: 400 !important;
}

.swal2_he {
  text-align: center;
  color: #545454;
  font-size: 1.125em;
  font-weight: 300;
  line-height: normal;
  word-wrap: break-word;
}
</style>
